---
import PageLayout from "@/layouts/Base";
import BlogPostPreview from "@/components/BlogPostPreview";
import { getAllTags, sortMDByDate } from "@/util";
import type { MDXInstance, Page, Post } from "@/types";

export async function getStaticPaths({ paginate }) {
	const allPosts = await Astro.glob<Post>("../../posts/*.mdx");
	const allPostsByDate = sortMDByDate(allPosts);
	const allTags = getAllTags(allPostsByDate);

	return allTags.map((tag) => {
		const filterPosts = allPostsByDate.filter((post) =>
			post.frontmatter.tags?.includes(tag)
		);
		return paginate(filterPosts, {
			params: { tag },
			pageSize: 10,
		});
	});
}

export interface Props {
	page: Page<MDXInstance<Post>>;
}

const { page } = Astro.props as Props;
const { tag } = Astro.params;

const meta = {
	title: `Tag: ${tag}`,
	description: `View all posts tagged with ${tag}`,
};
---

<PageLayout meta={meta}>
	<h1 class="flex items-center mb-6 title">
		Tag: {tag}
	</h1>
	<section aria-label="Blog post list">
		<ul class="text-left space-y-8">
			{
				page.data.map((p) => (
					<li class="flex flex-wrap items-center gap-x-2 [&_q]:w-full">
						<BlogPostPreview post={p} as="h2" withDesc />
					</li>
				))
			}
		</ul>
	</section>
</PageLayout>
